class AccountGroup < ActiveRecord::Base
  has_paper_trail :version => :paper_trail_version, :versions => :paper_trail_versions
  attr_accessible :default, :description, :group_name, :is_recommander, :levels
  validates_presence_of :group_name
  has_many :accounts, dependent: :nullify
  validates_uniqueness_of :default,:if => Proc.new{|ag| ag.default == true }

  def to_s
    group_name
  end

  after_save :move_accounts_to_default_group,:update_accounts_is_recommander

  def move_accounts_to_default_group
    if self.default
      Account.where(account_group_id: nil).update_all(account_group_id: self.id)
      AccountGroup.reset_counters self.id, :accounts
    end
  end

  def update_accounts_is_recommander
    if self.is_recommander
      Account.where(account_group_id: self.id,is_recommander: false).update_all(is_recommander: true)
    else
      Account.where(account_group_id: self.id,is_recommander: true).update_all(is_recommander: false)
    end
  end

end
